package luit.mmt02.secutity;

import java.io.File;
import java.io.FileOutputStream;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.os.Environment;
import android.util.Base64;
import android.util.Log;

public class webserviceRequest 
{
	private static String METHOD_CREATE_KEY = "getkeyStringEncrypt";
	private static String METHOD_GETKEY_DE = "getkeyStringDecrypt";
	private static String METHOD_GET_MYRSAKEY = "getRSAKey";
	private static String METHOD_GET_PURSAKEY = "getRSAKey_pu";
	private static String PATH_GET_KEY_DE = "/EncryptEmail/getkey_de/";
	private static String NAMESPACE = "http://mmt02.uit/";
//	private static String URL = "http://171.237.91.5:8080/emailkeyws/ws?wsdl";////
	//private static String URL = "http://192.168.1.6:8084/emailkeyws/ws?wsdl";
	//private static String URL = "http://10.201.227.50:8084/emailkeyws/ws?wsdl";	
	//private static String URL = "http://khoaluanmmt02-665.jelastic.servint.net:80/emailkeyws/ws?wsdl";	
	private static String URL = "http://khoaluanmmt02-665.jelastic.servint.net/emailkeyws/ws?wsdl";
	private static String SOAP_ACTION = "ws";		
	private static String METHOD_NAME = "";
	SoapSerializationEnvelope envelope;
	SoapObject request;
	HttpTransportSE androidHttpTransport;
	String str_namekeyfile;
	String str_pathkey;
	String str_nguoigui_nguoinhan, str_loaimahoa, str_nguoigui;////
	String str_nguoigui_nguoinhan_encrypted, str_loaimahoa_encrypt, str_nguoigui_encrypted;////
	sendingSecurity sendSecure;
	String tag = "WebserviceRequest";
	
	public webserviceRequest(String nguoigui_nguoinhan, String loaimahoa){
		this.str_nguoigui_nguoinhan = nguoigui_nguoinhan;
		this.str_nguoigui = nguoigui_nguoinhan.split(" ")[0];
		this.str_loaimahoa = loaimahoa;//AES, DES, 3DES, RSApu, RSApi;
		sendSecure = new sendingSecurity();
		this.str_nguoigui_nguoinhan_encrypted = sendSecure.Encrypt(nguoigui_nguoinhan);
		this.str_loaimahoa_encrypt = sendSecure.Encrypt(loaimahoa);
		this.str_nguoigui_encrypted = sendSecure.Encrypt(str_nguoigui);
	}
	
	public void getkeyStringEncrypt(){
		tag = "requesWebService()";
		requestWebService();
	}
	
	public void getkeyStringDecrypt(){
		tag = "requestWebService2()";
		requestWebService2();
	}
	//yeu cau server tra ve public key va private key de ky;
	public void getMyRSAKey(){
		tag = "requestMyRSAKey";
		requestMyRSAKey();
	}
	//yeu cau server tra ve public key de xac nhan chu ky;t
	public void getPuRSAKey_sign(){
		tag = "requestPuRSAKey()";
		requestPuRSAKey_sign();
	}
	
	public void getPuRSAKey_encrypt(String str_nguoinhan){
		tag = "requestPubFSAKey_encrypt()";
		str_nguoigui = str_nguoinhan;
		str_nguoigui_encrypted = sendSecure.Encrypt(str_nguoinhan);
		requestPuRSAKey_encrypt();
	}
	
	public void requestPuRSAKey_encrypt(){
		////lay public key cua nguoi nhan de ma hoa roi gui cho nguoi nhan, nguoi nhan dung private key cua no de giai ma;
			str_namekeyfile = str_nguoigui+" keypu.key";
			str_pathkey = Environment.getExternalStorageDirectory().getAbsolutePath()+PATH_GET_KEY_DE+str_namekeyfile;
			Log.v(tag, "str_pathkey="+str_pathkey);
			request = new SoapObject(NAMESPACE, METHOD_GET_MYRSAKEY);
			request.addProperty("nguoigui", str_nguoigui_encrypted);//bien truyen vao la nguoi nhan = str_nguoinhan;
			request.addProperty("loaiRSA", str_loaimahoa_encrypt);//bien truyen vao chi la "RSApu";
			envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			envelope.setOutputSoapObject(request);
			envelope.dotNet = false;
			androidHttpTransport = new HttpTransportSE(URL);
			try{
				androidHttpTransport.call(SOAP_ACTION, envelope);
				SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
				String keyString = result.toString();
				keyString = sendSecure.Decrypt(keyString);////
				Log.v( tag,"RESULT="+keyString);
				
				if(keyString.equalsIgnoreCase("NULL")){
					Log.v(tag,"RESULT=NULL <--> ERROR :  tao key loi");
				}
				else {
					
						if (keyString != null) {
							byte[] decoded = Base64.decode(keyString, 0);						
							File keyfile = new File(str_pathkey);						
							FileOutputStream os = new FileOutputStream(keyfile);
							Log.v(tag, "Da luu file key RSA thanh cong:"+str_namekeyfile);
							os.write(decoded);
							os.close();
						}
					
				}
				
			}catch(Exception e){
				Log.v(tag, "ERROR: "+e);
			}
	}
	public void requestPuRSAKey_sign(){
			////lay ve public key: ten file: nguoigui keypu.key ve de xac thuc chu ky;

			str_namekeyfile = str_nguoigui+" "+"keypu.key";
			str_pathkey = Environment.getExternalStorageDirectory().getAbsolutePath()+"/EncryptEmail/getkey_de/"+str_namekeyfile;
			Log.v(tag, str_pathkey);
			request = new SoapObject(NAMESPACE, METHOD_GET_PURSAKEY);
			request.addProperty("nguoigui", str_nguoigui_encrypted);//@WebParam(name = "myparameter"):must
			envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			envelope.setOutputSoapObject(request);
			envelope.dotNet = false;
			androidHttpTransport = new HttpTransportSE(URL);
			try{
				androidHttpTransport.call(SOAP_ACTION, envelope);
				SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
				String keyString = result.toString();
				keyString = sendSecure.Decrypt(keyString);////
				Log.v(tag,"RESULT="+keyString);
				
				if(keyString.equalsIgnoreCase("NULL")){
					Log.v(tag,"RESULT=NULL <--> ERROR :  ko lay duoc key");
				}
				else {
					
						if (keyString != null) {
							byte[] decoded = Base64.decode(keyString, 0);						
							File keyfile = new File(str_pathkey);						
							FileOutputStream os = new FileOutputStream(keyfile);
							Log.i(tag, "Da luu file pulblic key thanh cong:"+str_namekeyfile);
							os.write(decoded);
							os.close();
						}
					
				}
				
			}catch(Exception e){
				Log.v(tag, "ERROR: "+e);
			}
	}
	
	public void requestMyRSAKey(){
		////loaiRSA = RSApu or RSApi;//tao cap key: public key va private key roi tra ve theo yeu cau: public key hoac private key
		if(str_loaimahoa.equalsIgnoreCase("RSApu")){
			str_namekeyfile = str_nguoigui+" keypu.key";
		}else str_namekeyfile = str_nguoigui+" keypri.key";

		str_pathkey = Environment.getExternalStorageDirectory().getAbsolutePath()+"/EncryptEmail/keymail/"+str_namekeyfile;
		Log.v(tag, "str_pathkey="+str_pathkey);
		request = new SoapObject(NAMESPACE, METHOD_GET_MYRSAKEY);
		request.addProperty("nguoigui", str_nguoigui_encrypted);//@WebParam(name = "myparameter"):must
		request.addProperty("loaiRSA", str_loaimahoa_encrypt);
		envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
		envelope.setOutputSoapObject(request);
		envelope.dotNet = false;
		androidHttpTransport = new HttpTransportSE(URL);
		try{
			androidHttpTransport.call(SOAP_ACTION, envelope);
			SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
			String keyString = result.toString();
			keyString = sendSecure.Decrypt(keyString);////
			Log.v( tag,"RESULT="+keyString);
			
			if(keyString.equalsIgnoreCase("NULL")){
				Log.v(tag,"RESULT=NULL <--> ERROR :  tao key loi");
			}
			else {
				
					if (keyString != null) {
						byte[] decoded = Base64.decode(keyString, 0);						
						File keyfile = new File(str_pathkey);						
						FileOutputStream os = new FileOutputStream(keyfile);
						Log.v(tag, "Da luu file key RSA thanh cong:"+str_namekeyfile);
						os.write(decoded);
						os.close();
					}
				
			}
			
		}catch(Exception e){
			Log.v(tag, "ERROR: "+e);
		}
	}
	public void requestWebService(){
		str_namekeyfile = str_nguoigui_nguoinhan+" "+str_loaimahoa;////
		str_pathkey = Environment.getExternalStorageDirectory().getAbsolutePath()+"/EncryptEmail/keymail/"+str_namekeyfile;
		Log.v(tag, "str_pathkey="+str_pathkey);
		request = new SoapObject(NAMESPACE, METHOD_CREATE_KEY);
		request.addProperty("nguoigui_nguoinhan", str_nguoigui_nguoinhan_encrypted);//@WebParam(name = "myparameter"):must
		request.addProperty("loaimahoa", str_loaimahoa_encrypt);
		envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
		envelope.setOutputSoapObject(request);
		envelope.dotNet = false;
		androidHttpTransport = new HttpTransportSE(URL);
		try{
			androidHttpTransport.call(SOAP_ACTION, envelope);
			SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
			String keyString = result.toString();
			keyString = sendSecure.Decrypt(keyString);////
			Log.v( tag,"RESULT="+keyString);
			
			if(keyString.equalsIgnoreCase("NULL")){
				Log.v(tag,"RESULT=NULL <--> ERROR :  tao key loi");
			}
			else {
				
					if (keyString != null) {
						byte[] decoded = Base64.decode(keyString, 0);						
						File keyfile = new File(str_pathkey);						
						FileOutputStream os = new FileOutputStream(keyfile);
						Log.v(tag, "Da luu file key thanh cong:"+str_namekeyfile);
						os.write(decoded);
						os.close();
					}
				
			}
			
		}catch(Exception e){
			Log.v(tag, "ERROR: "+e);
		}
	}
	
	//// KEY GET
		public void requestWebService2(){
			str_namekeyfile = str_nguoigui_nguoinhan+" "+str_loaimahoa;////
			str_pathkey = Environment.getExternalStorageDirectory().getAbsolutePath()+ PATH_GET_KEY_DE + str_namekeyfile;
			Log.v(tag, "str_pathkey="+str_pathkey);
			request = new SoapObject(NAMESPACE, METHOD_GETKEY_DE);
			request.addProperty("nguoigui_nguoinhan", str_nguoigui_nguoinhan_encrypted);//@WebParam(name = "myparameter"):must
			request.addProperty("loaimahoa", str_loaimahoa_encrypt);
			envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			envelope.setOutputSoapObject(request);
			envelope.dotNet = false;
			androidHttpTransport = new HttpTransportSE(URL);
			try{
				androidHttpTransport.call(SOAP_ACTION, envelope);
				SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
				String keyString = result.toString();
				keyString = sendSecure.Decrypt(keyString);////
				Log.v(tag,"RESULT="+keyString);
				
				if(keyString.equalsIgnoreCase("NULL")){
					Log.v(tag,"RESULT=NULL <--> ERROR :  tao key loi");
				}
				else {
					
						if (keyString != null) {
							Log.v(tag, "bat dau ghi  get key ....");
							byte[] decoded = Base64.decode(keyString, 0);						
							File keyfile = new File(str_pathkey);
							if(!keyfile.isFile())
							{
								keyfile.createNewFile();
								FileOutputStream os = new FileOutputStream(keyfile);
								Log.v(tag, "Da luu file key thanh cong");
								os.write(decoded);
								os.close();
							}
							else
								Log.v(tag, "key da ton tai ");
							
						}
					
				}
				
			}catch(Exception e){
				Log.v(tag, "ERROR: "+e.toString());
			}
		}
	
	
/*	public void getkeyStringEncrypt(String str_nguoigui_nguoinhan, String str_loaimahoa){
//		METHOD_NAME = "getkeyStringEncrypt";//name method in webservice: @WebMethod(operationName = "myoperation");
		requestWebService(METHOD_CREATE_KEY, str_nguoigui_nguoinhan, str_loaimahoa);
	}
	
	public void getkeyStringDecrypt(String str_nguoigui_nguoinhan, String str_loaimahoa){
//		METHOD_NAME = "getkeyStringDecrypt";//name method in webservice: @WebMethod(operationName = "myoperation");
		requestWebService2(METHOD_GETKEY_DE, str_nguoigui_nguoinhan, str_loaimahoa);
	}*/
	
	/*public void requestWebService(String methodname, String str_nguoigui_nguoinhan, String str_loaimahoa){
		///str_namekeyfile = str_nguoigui_nguoinhan+str_loaimahoa+".key";
		str_namekeyfile = str_nguoigui_nguoinhan+" "+str_loaimahoa;////
		str_pathkey = Environment.getExternalStorageDirectory().getAbsolutePath()+"/EncryptEmail/keymail/"+str_namekeyfile;
//		str_pathkey = Environment.getExternalStorageDirectory().getAbsolutePath() + "/aaaa.key";
		//nameVoiceGet = "b.wmv";
		request = new SoapObject(NAMESPACE, methodname);
		request.addProperty("nguoigui_nguoinhan", str_nguoigui_nguoinhan);//@WebParam(name = "myparameter"):must
		request.addProperty("loaimahoa", str_loaimahoa);
		envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
		envelope.setOutputSoapObject(request);
		envelope.dotNet = false;
		androidHttpTransport = new HttpTransportSE(URL);
		try{
			androidHttpTransport.call(SOAP_ACTION, envelope);
			SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
			String keyString = result.toString();
			Log.i("RESULT getkeyStringEncrypt =",keyString);
			
			if(keyString.equalsIgnoreCase("NULL")){
				Log.i("RESULT getkeyStringEncrypt =","ERROR :  tao key loi");
			}
			else {
				
					if (keyString != null) {
						byte[] decoded = Base64.decode(keyString, 0);						
						File keyfile = new File(str_pathkey);						
						FileOutputStream os = new FileOutputStream(keyfile);
						Log.i("TAO KEY", "Da luu file thanh cong");
						os.write(decoded);
						os.close();
					}
				
			}
			
		}catch(Exception e){
			Log.i("getkeyStringEncrypt", "ERROR: "+e);
		}
	}*/
	
	
	
	public void gethello(String name){
		METHOD_NAME = "hello";
		request = new SoapObject(NAMESPACE, METHOD_NAME);
		request.addProperty("name", sendSecure.Encrypt(name));//@WebParam(name = "name"):must////
		envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
		envelope.setOutputSoapObject(request);
		envelope.dotNet = false;
		androidHttpTransport = new HttpTransportSE(URL);
		try{
			androidHttpTransport.call(SOAP_ACTION, envelope);
			SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
			String ketqua = result.toString();
			Log.i("CONNECT SERVER", "thanh cong result = "+sendSecure.Decrypt(ketqua));
		}catch(Exception e){
			Log.i("hello", "ERROR: "+e);
		}
	}
	
	/*/// KEY GET
	public void requestWebService2(String methodname, String str_nguoigui_nguoinhan, String str_loaimahoa){
		///str_namekeyfile = str_nguoigui_nguoinhan+str_loaimahoa+".key";
		str_namekeyfile = str_nguoigui_nguoinhan+" "+str_loaimahoa;////
		str_pathkey = Environment.getExternalStorageDirectory().getAbsolutePath()+ PATH_GET_KEY_DE + str_namekeyfile;
		Log.v(tag, "path save : " + str_pathkey);
//		str_pathkey = Environment.getExternalStorageDirectory().getAbsolutePath() + "/aaaa.key";
		request = new SoapObject(NAMESPACE, methodname);
		request.addProperty("nguoigui_nguoinhan", str_nguoigui_nguoinhan);//@WebParam(name = "myparameter"):must
		request.addProperty("loaimahoa", str_loaimahoa);
		envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
		envelope.setOutputSoapObject(request);
		envelope.dotNet = false;
		androidHttpTransport = new HttpTransportSE(URL);
		try{
			androidHttpTransport.call(SOAP_ACTION, envelope);
			SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
			String keyString = result.toString();
			Log.i("RESULT getkeyStringEncrypt =",keyString);
			
			if(keyString.equalsIgnoreCase("NULL")){
				Log.i("RESULT getkeyStringEncrypt =","ERROR :  tao key loi");
			}
			else {
				
					if (keyString != null) {
						Log.v(tag, "bat dau ghi get key ....");
						byte[] decoded = Base64.decode(keyString, 0);						
						File keyfile = new File(str_pathkey);
						if(!keyfile.isFile())
						{
							keyfile.createNewFile();
							FileOutputStream os = new FileOutputStream(keyfile);
							Log.i("TAO KEY", "Da luu file thanh cong");
							os.write(decoded);
							os.close();
						}
						else
							Log.v(tag, "key da ton tai ");
						
					}
				
			}
			
		}catch(Exception e){
			Log.i("getkeyStringEncrypt", "ERROR: "+e.toString());
		}
	}*/
}
